package com.ruoyi.demo.util;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.demo.controller.VideoCaptureController;
import com.ruoyi.demo.domain.MeetAgenda;
import com.ruoyi.demo.mapper.MeetAgendaMapper;
import com.ruoyi.system.domain.Meet;
import com.ruoyi.system.mapper.MeetMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@Component
public class RegisterTask {
    @Autowired
    private VideoCaptureController videoCaptureController;
    @Autowired
    private MeetAgendaMapper meetAgendaMapper;
    @Autowired
    private MeetMapper meetMapper;

    private static final Logger log = LoggerFactory.getLogger(RegisterTask.class);
    
    // 用于控制任务是否在运行
    private final AtomicBoolean isTaskRunning = new AtomicBoolean(false);
    private volatile long nextRunTime = 0;

    @Scheduled(fixedDelay = 1000)
    public void register() {
        // 如果任务正在运行或者还没到下次运行时间，直接返回
        if (isTaskRunning.get() || System.currentTimeMillis() < nextRunTime) {
            return;
        }

        try {
            log.info("开始检查签到时间...");
            List<MeetAgenda> agendas = meetAgendaMapper.selectRegisterTime();

            for (MeetAgenda agenda : agendas) {
                if ("会议签到".equals(agenda.getAgendaTitle())) {
                    Meet meet = meetMapper.selectMeetByMeetId(agenda.getMeetId().intValue());
                    long signinStartMillis = agenda.getStartTime().getTime();
                    long signinEndMillis = agenda.getEndTime().getTime();
                    long currentTimeMillis = System.currentTimeMillis();

                    if (meet != null) {
                        // 计算签到持续时间（秒）
                        long durationMillis = signinEndMillis - signinStartMillis - 3000;
                        int durationSeconds = (int)(durationMillis / 1000);
                        
                        log.info("发现需要签到的会议：{}，持续时间：{}秒，开始时间：{}", 
                            meet.getMeetId(), durationSeconds, new Date(signinStartMillis));
                        
                        try {
                            // 设置任务状态为运行中
                            isTaskRunning.set(true);
                            
                            // 直接调用VideoCaptureController
                            log.info("开始调用签到接口，持续时间：{}秒", durationSeconds);
                            AjaxResult result = videoCaptureController.record(durationSeconds);
                            log.info("调用签到接口返回结果：{}", result.toString());
                            
                            if (result.isSuccess()) {
                                // 设置下次运行时间
                                nextRunTime = System.currentTimeMillis() + (durationSeconds * 1000L);
                                log.info("签到任务启动成功，将在 {} 秒后恢复扫描", durationSeconds);
                                
                                // 启动一个新线程在指定时间后重置状态
                                new Thread(() -> {
                                    try {
                                        Thread.sleep(durationSeconds * 1000L);
                                    } catch (InterruptedException e) {
                                        Thread.currentThread().interrupt();
                                    } finally {
                                        isTaskRunning.set(false);
                                        log.info("签到任务结束，状态已重置");
                                    }
                                }).start();
                            } else {
                                isTaskRunning.set(false);
                                nextRunTime = 0;
                                log.error("调用签到接口失败：{}", result.get("msg"));
                            }
                            
                        } catch (Exception e) {
                            log.error("调用签到接口异常：", e);
                            isTaskRunning.set(false);
                            nextRunTime = 0;
                        }
                        // 找到并处理了一个任务后就退出循环
                        break;
                    }
                }
            }
        } catch (Exception e) {
            log.error("签到任务异常：", e);
            isTaskRunning.set(false);
            nextRunTime = 0;
        }
    }
}
